/* 局部引入的工具类 */

function createCaptcha(context, width, height, captcha) {
  // 初始化验证码, captcha存在则指定验证码内容
  // let context = uni.createCanvasContext('imgcanvas', this)
  let w = width / 750 * uni.getSystemInfoSync().screenWidth;
  let h = height;
  context.setFillStyle("white");
  context.setLineWidth(5);
  context.fillRect(0, 0, w, h);
  let pool = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "I", "M", "N", "O", "P", "Q", "R", "S",
      "T", "U", "V", "W", "S", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"
    ],
    str = '';
  for (let i = 0; i < 4; i++) {
    // 构造字符串
    let c = captcha ? captcha.charAt(i) : pool[rn(0, pool.length - 1)];

    let deg = rn(-30, 30);
    context.setFontSize(18);
    context.setTextBaseline("top");
    context.setFillStyle(rc(80, 150));
    context.save();
    context.translate(30 * i + 15, parseInt(h / 1.5));
    context.rotate(deg * Math.PI / 180);
    context.fillText(c, -15 + 5, -15);
    context.restore();
    str += c;
  }
  for (let i = 0; i < 40; i++) {
    // 模糊背景
    context.beginPath();
    context.arc(rn(0, w), rn(0, h), 1, 0, 2 * Math.PI);
    context.closePath();
    context.setFillStyle(rc(150, 200));
    context.fill();
  }
  context.draw();
}

function rc(min, max) {
  // 创建验证码需要
  let r = rn(min, max);
  let g = rn(min, max);
  let b = rn(min, max);
  return `rgb(${r},${g},${b})`
}

function rn(max, min) {
  // 创建验证码需要
  return parseInt(Math.random() * (max - min)) + min;
}

function copy(text) {
  // 跨端复制功能
  // #ifdef H5
  const btn = document.querySelector('.copy_tkl');
  const input = document.createElement('input');
  input.setAttribute('readonly', 'readonly');
  input.setAttribute('value', text);
  document.body.appendChild(input);
  input.select();
  input.setSelectionRange(0, 9999);
  if (document.execCommand('copy')) {
    document.execCommand('copy');
    uni.showToast({
      title: '复制成功'
    });
  }
  document.body.removeChild(input);
  // #endif
  // #ifndef H5
  uni.setClipboardData({
    data: text,
    success: () => {
      uni.showToast({
        title: '复制成功'
      });
    }
  });
  // #endif
}

function getRoute(){
  let pages = getCurrentPages();
  let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
  let curRoute = routes[routes.length - 1].route; //获取当前页面路由
  let curParam = routes[routes.length - 1].options; //获取路由参数
  // 拼接参数
  let param = '';
  for (let key in curParam) {
    if (param === '') {
      param += key + '=' + curParam[key];
    } else {
      param += '&' + key + '=' + curParam[key];
    }
  }
  let route = {
    path: curRoute, // 页面路径，开头不带/      pages/index/index
    param: param, // 页面参数，如a=1&b=2
  }
  return route
}

/*
 *获取当前URL中的指定参数
 */
function GetQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
};

//替换指定传入URL参数的值,paramName为参数,replaceWith为新值
function replaceParamVal(href, paramName, replaceWith) {
  var oUrl = href;
  var re = eval('/(' + paramName + '=)([^&]*)/gi');
  var nUrl = oUrl.replace(re, paramName + '=' + replaceWith);
  this.location = nUrl;
  return nUrl
}

// 单个文件上传工具类
async function UploadFile(file, channelId) {
  // #ifdef H5
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: (process.env.NODE_ENV === 'development' ? 'http://zsgh.center999.com/' : Config.domain) +
        'api/common/nupload',
      filePath: file,
      name: 'file',
      formData: {
        channelId: channelId || ''
      },
      header: {},
      success: (res) => {
        if (res.statusCode == 200) {
          if(JSON.parse(res.data).code === 0){
            uni.showToast({
              icon: 'none',
              title: JSON.parse(res.data).msg || '文件上传失败'
            })
            reject(res || 'false')
          }else{
            resolve(JSON.parse(res.data))
          }
        }
      },
      fail: (err) => {
        reject(err || 'false')
      }
    })
  })
  // #endif
  // #ifdef MP-WEIXIN
  // let FormData = new formData();
  // // 图片类型
  // FormData.appendFile('file', file.path);
  // // 字段类型
  // FormData.append('channelId', channelId || '');
  // let json = FormData.getData()
  // let data = json.buffer;
  // let contentType = json.contentType;

  // return new Promise((resolve, reject) => {
  //   API.common.uploadFileToQN(data).then(res => {
  //     resolve(res)
  //   }).catch(err => {
  //     reject('false')
  //   })
  // })
  // #endif
}
export {
  createCaptcha,
  copy,
  getRoute,
  GetQueryString,
  replaceParamVal,
  UploadFile,
}
